const app = getApp();

Page({
  data: {
    userId: null,        // 当前用户ID（从Token解析）
    userRooms: [],       // 后端返回的房间列表
    isLoading: false,     // 加载状态（提升用户体验）
    showCreateRoomModal: false, // 创建房间弹窗状态
    createRoomId: ''
  },

  // 页面加载时触发
  onLoad() {
    // 先解析Token获取用户ID（为后续请求做准备）
    this.parseUserIdFromToken();
  },

  // 页面每次显示时刷新列表（比如从聊天室返回后更新状态）
  onShow() {
    if (this.data.userId) {
      this.getUserRoomsFromServer(); // 调用后端接口获取房间列表
    }
  },

  // 1. 从Token解析用户ID
  parseUserIdFromToken() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      wx.redirectTo({ url: '/pages/login/login' });
      return;
    }

    try {
      // 解析JWT Token的payload部分
      const tokenParts = token.split('.');
      if (tokenParts.length !== 3) {
        throw new Error('Token格式错误');
      }
      // Base64URL解码
      const base64 = tokenParts[1].replace(/-/g, '+').replace(/_/g, '/');
      const padLength = (4 - (base64.length % 4)) % 4;
      const paddedBase64 = base64 + '='.repeat(padLength);
      // 解码并转换为JSON
      const decodedStr = atob(paddedBase64);
      const payload = JSON.parse(decodedStr);
     
      const userId = payload.id || null;
      if (!userId) {
        throw new Error('Token中无用户ID');
      }
      this.setData({ userId: String(userId) }); 
    } catch (error) {
      wx.showToast({ title: '登录状态无效', icon: 'none' });
      wx.redirectTo({ url: '/pages/login/login' });
    }
  },


  getUserRoomsFromServer() {
    const token = wx.getStorageSync('token');
    if (!token) return;

    this.setData({ isLoading: true });

    wx.request({
      url: 'http://localhost:8080/api/room/userRooms', 
      method: 'GET',
      header: {
        'token': token, 
        'content-type': 'application/json'
      },
      success: (res) => {
        this.setData({ isLoading: false });

        if (res.data && res.data.code === 200) {
          const rooms = res.data.data || [];
          this.setData({ userRooms: rooms });
          
          wx.setStorageSync(`userRooms_${this.data.userId}`, rooms);
        } else {
       
          wx.showToast({ title: res.data.msg || '加载失败', icon: 'none' });
       
          if (res.data.code === 401) {
            wx.redirectTo({ url: '/pages/login/login' });
          }
        }
      },
      fail: (error) => {
    
        this.setData({ isLoading: false });
        wx.showToast({ title: '网络错误，请检查连接', icon: 'none' });
    
        const cachedRooms = wx.getStorageSync(`userRooms_${this.data.userId}`) || [];
        if (cachedRooms.length > 0) {
          this.setData({ userRooms: cachedRooms });
          wx.showToast({ title: '已加载缓存数据', icon: 'none' });
        }
      }
    });
  },


  gotoChatRoom(e) {
    // 获取点击的房间ID
    const roomId = e.currentTarget.dataset.roomid;
    if (!roomId) {
      wx.showToast({ title: '房间ID无效', icon: 'none' });
      return;
    }

    // 跳转到聊天室页面，并携带roomId参数
    wx.navigateTo({
      url: `/pages/room/room?roomId=${roomId}`, 
      success: () => {
        wx.showToast({ title: `进入房间 ${roomId}`, icon: 'none', duration: 800 });
      }
    });
  },
  showRoomIdInput() {
    this.setData({
      showRoomInputModal: true,
      inputRoomId: ''
    });
  },

  // 取消输入
  cancelEnterRoom() {
    this.setData({
      showRoomInputModal: false
    });
  },

  // 监听房间号输入
  onRoomIdInput(e) {
    this.setData({
      inputRoomId: e.detail.value.trim()
    });
  },

  // 确认进入房间
  confirmEnterRoom() {
    const roomId = this.data.inputRoomId;
    if (!roomId) {
      wx.showToast({ title: '请输入房间号', icon: 'none' });
      return;
    }
    if (!/^\d+$/.test(roomId)) {
      wx.showToast({ title: '房间号必须是数字', icon: 'none' });
      return;
    }
  
    wx.request({
      url: 'http://localhost:8080/api/room/exists',
      method: 'GET',
      data: { roomId },
      header: {
        'token': wx.getStorageSync('token'),
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200) {
        
          this.setData({ showRoomInputModal: false });
          wx.navigateTo({
            url: `/pages/room/room?roomId=${roomId}`,
            success: () => {
              wx.showToast({ title: `进入房间 ${roomId}`, icon: 'none', duration: 800 });
            }
          });
        } else {
         
          wx.showToast({ title: res.data.msg || '房间不存在', icon: 'none' });
        }
      },
      fail: (error) => {
        wx.showToast({ title: '网络错误，请稍后再试', icon: 'none' });
      }
    });
  },
  //创建房间
  showCreateRoomModal() {
    this.setData({
      showCreateRoomModal: true,
      createRoomId: '' // 重置输入值
    });
  },

  // 2. 取消创建房间（关闭弹窗）
  cancelCreateRoom() {
    this.setData({
      showCreateRoomModal: false
    });
  },

  // 3. 监听创建房间号输入
  onCreateRoomIdInput(e) {
    this.setData({
      createRoomId: e.detail.value.trim()
    });
  },

  // 4. 确认创建房间（核心逻辑：校验+调用后端接口）
  confirmCreateRoom() {
    const roomId = this.data.createRoomId;
    const userId = this.data.userId;

    // 校验规则：0开头、≤8位、纯数字
    if (!roomId) {
      wx.showToast({ title: '请输入房间号', icon: 'none' });
      return;
    }
    if (roomId[0] !== '0') {
      wx.showToast({ title: '房间号必须以0开头', icon: 'none' });
      return;
    }
    if (!/^\d+$/.test(roomId)) {
      wx.showToast({ title: '房间号必须是纯数字', icon: 'none' });
      return;
    }
    if (roomId.length > 8) {
      wx.showToast({ title: '房间号不能超过8位', icon: 'none' });
      return;
    }

    // 调用后端创建房间接口（需后端配合新增）
    const token = wx.getStorageSync('token');
    wx.request({
      url: 'http://localhost:8080/api/room/create',
      method: 'POST',
      header: {
        'token': token,
        'content-type': 'application/json'
      },
      data: { roomId, userId }, // 传递房间号和创建者ID
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({ title: '房间创建成功' });
          this.setData({ showCreateRoomModal: false });
          // 跳转至新创建的房间
          wx.navigateTo({
            url: `/pages/room/room?roomId=${roomId}`,
            success: () => {
              wx.showToast({ title: `进入房间 ${roomId}`, icon: 'none', duration: 800 });
            }
          });
        } else {
          wx.showToast({ title: res.data.msg || '房间创建失败', icon: 'none' });
        }
      },
      fail: (error) => {
        wx.showToast({ title: '网络错误，请稍后再试', icon: 'none' });
      }
    });
  }
});